<template>
  <div>
    <el-button type="primary" @click="add">添加</el-button>
    <el-table :data="tableData" border style="width: 100%">
      <el-table-column prop="id" label="ID" width="120"></el-table-column>
      <el-table-column prop="name" label="姓名" width="120"></el-table-column>
      <el-table-column prop="city" label="市区" width="120"></el-table-column>
      <el-table-column prop="address" label="地址" width="300"></el-table-column>
      <el-table-column fixed="right" label="操作" width="100">
        <template slot-scope="scope">
          <el-button @click="remove(scope.row)" type="text" size="small">删除</el-button>
          <el-button @click="change(scope.row)" type="text" size="small">编辑</el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>


<script>
export default {
  data() {
    return {
      tableData: [{
        name: "",
        city: "",
        address: ""
      }]
    };
  },
  methods: {
    add() {
      this.$router.push("/add");
    },
    async remove(row) {
      const res = await this.$http.delete(`user/${row.id}`);
      res.data.success ? this.$message({ type: "success", message: "删除成功"}) : this.$message.error("删除失败，请稍后重试");
    },
    async change(row) {
      this.$router.push({
        name: "/add",
        params: {
          id: row.id,
          row
        }
      });
    },
    async fetch() {
      const res = await this.$http.get("/user");
      this.tableData = res.data.data;
    },
  },
  created() {
    this.fetch();
  }
};
</script>

